#!/usr/bin/env bash

# This generates blocks of land on ocean
# and output is the terrain layer, startpos (blank),
# and the other layers needed for Freeciv 2.6.4 through 2.6.11 scenarios

# Ouput a blank line
echo

# Declare variables
declare    zeroPad="0000" tile layerPrefix lineOfSpaces
declare -a terrain_layer
declare -i x y r breaks

# The map size is determined by the xsize and ysize variables on the next line
# and those can be set from the command line when invoking the script by adding 80 60, for example
declare -i xsize="${1:-92}" ysize="${2:-46}"

if [ ${xsize} -lt 30 ] || [ ${ysize} -lt 30 ] ; then
	echo "Too small, try x and y sizes greater or equal to 30"
	echo
	exit 1
fi

printf -v lineOfSpaces '%*s ' $(( ${xsize} - 1 ))

# Ouput a blank line
echo

for (( y=0 ; y<${ysize} ; y++ )) ; do
	for (( x=0 ; x<${xsize} ; x++ )) ; do

		r=$(( 1 + RANDOM % 19 ))

		# No lake tiles, add them later
		if [ ${r} -ge 1 ] && [ ${r} -le 5 ] ; then tile="g" ; fi
		if [ ${r} -ge 6 ] && [ ${r} -le 9 ] ; then tile="p" ; fi
		if [ ${r} -ge 10 ] && [ ${r} -le 12 ] ; then tile="h" ; fi
		if [ ${r} -ge 13 ] && [ ${r} -le 15 ] ; then tile="f" ; fi
		if [ ${r} -eq 16 ] ; then tile="m" ; fi
		if [ ${r} -eq 17 ] ; then tile="d" ; fi
		if [ ${r} -eq 18 ] ; then tile="j" ; fi
		if [ ${r} -eq 19 ] ; then tile="s" ; fi

		breaks=$(( ( ( "${xsize}" / 6 ) + ( "${ysize}" / 6 ) ) / 2 ))

		if [ "${x}" -ge 0 -a $(( "${x}" % "${breaks}" )) -ge 0 -a $(( "${x}" % "${breaks}" )) -lt 4 ] ; then
			tile=" "
		fi

		if [ "${y}" -ge 0 -a $(( "${y}" % "${breaks}" )) -ge 0 -a $(( "${y}" % "${breaks}" )) -lt 4 ] ; then
			tile=" "
		fi

		terrain_layer[${y}]="${terrain_layer[${y}]}${tile}"
	done
done

# Output the map sections formatted for at least, Freeiv 2.6.4 through 2.6.11
for (( y=0 ; y<${ysize} ; y++ )) ; do
	echo "t${zeroPad:${#y}}${y}=\"${terrain_layer[${y}]}\""
done

# Output the startpos info (blocks of land do well with startpos defaults so no specific values needed)
echo -e 'startpos_count=0\nstartpos={"x","y","exclude","nations"\n}'

# Output the other layers
for layerPrefix in e00_ e01_ e02_ e03_ res ; do
	for (( y=0 ; y<${ysize} ; y++ )) ; do
		echo -n "${layerPrefix}${zeroPad:${#y}}${y}="
		if [ "${layerPrefix}" = "res" ] ; then
			echo "\"${lineOfSpaces}\""
		else
			echo "\"${lineOfSpaces// /0}\""
		fi
	done
done

# Ouput a blank line
echo

exit 0
